﻿using Dapper;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OMG.Fill.Mulberry.Model;
using OMG.Fill.Mulberry.Model.Ent;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace OMG.Fill.Mulberry.Service
{
    /// <summary>
    /// 表2季度生产情况表T_MulQuartProduc通用操作类
    /// </summary>
    public class MulQuartProducServices : MulQuartProducs
    {
        AreaServices area = new AreaServices();
        public Pager<List<MulQuartProducEntity>> GetPageList(MulQuartProducQuery query)
        {
            Pager<List<MulQuartProducEntity>> obj = new Pager<List<MulQuartProducEntity>>();
            var paramlist = new DynamicParameters();
            string strWhereSql = "";//from 表在下面，需完善其他查询条件在这里接的写，格式为："and xxx=@xxx空格,如下注释部分代码所示："
            //if (!string.IsNullOrEmpty(query.GroupCode))
            //{
            //  strWhereSql += "and GroupCode = @GroupCode ";
            //  paramlist.Add("GroupCode", query.GroupCode);
            //}
            string strFromSql = "from dbo.T_MulQuartProduc where 1=1 " + strWhereSql;
            string strTotal = "select count(1)" + strFromSql + strWhereSql;
            string strOrderSql = "";//自定义完成order by语句
            string strSql = @"select * from (select *,ROW_NUMBER() over (order by Id ) as RowNumber " + strFromSql + ") as t ";
            strSql += "where t.RowNumber between  @minRow and @maxRow" + strOrderSql;
            paramlist.Add("minRow", query.MinRow);
            paramlist.Add("maxRow", query.MaxRow);
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj.rows = dbCon.Query<MulQuartProducEntity>(strSql, paramlist).ToList();
                    obj.total = dbCon.Query<int>(strTotal, paramlist).FirstOrDefault();
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取表2季度生产情况表T_MulQuartProduc分页列表失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 获取指定对象
        /// </summary>
        public override ResResult<MulQuartProducEntity> GetModel(string ReportId)
        {
            ResResult<MulQuartProducEntity> obj = new ResResult<MulQuartProducEntity>();
            MulQuartProducEntity model = new MulQuartProducEntity();
            if (CheckRepCount(ReportId))
            {
                model.ReportId = ReportId;
                if (AddInfo(model).status > 0)
                {
                    obj.model = model;
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                }
            }
            else
            {
                string strSql = @"select * from dbo.T_MulQuartProduc where ReportId = @ReportId";
                try
                {
                    using (var dbCon = ConnectFactory.GetOpenConnection())
                    {
                        obj.model = dbCon.Query<MulQuartProducEntity>(strSql, new { ReportId = ReportId }).FirstOrDefault();
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "获取成功！";
                        dbCon.Dispose();//数据库连接释放
                    }
                }
                catch (Exception ex)
                {
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("获取表1桑园面积统计表T_MulQuartProduc对象信息失败", ex);

                }
            }
            return obj;
        }
        /// <summary>
        /// 判定是否生成过报表
        /// </summary>
        /// <param name="reportId"></param>
        /// <returns>没生成过true,否则false</returns>
        public bool CheckRepCount(string reportId)
        {
            string strSql = @"select count(1) from dbo.T_MulQuartProduc where ReportId=@ReportId";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    //为0，没生成过true,否则false
                    return dbCon.Query<int>(strSql, new { ReportId = reportId }).FirstOrDefault() == 0 ? true : false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("判断是否生成过表1桑园面积统计表T_MulQuartProduc失败", ex);
                return false;
            }
        }
        public override ResResult<int> UpdateInfo(MulQuartProducEntity model)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"UPDATE dbo.T_MulQuartProduc set ";
            strSql += "ReportId = @ReportId,";
            strSql += "SeedSize = @SeedSize,";
            strSql += "FreshCocoonYield = @FreshCocoonYield,";
            strSql += "AveFreshCocoon = @AveFreshCocoon,";
            strSql += "SmallRearSilk = @SmallRearSilk,";
            strSql += "GridCluster = @GridCluster,";
            strSql += "NextSeaOutPut = @NextSeaOutPut,";
            strSql += "NextSeaFresh = @NextSeaFresh";
            strSql += " where Id = @Id";

            using (var dbCon = ConnectFactory.GetOpenConnection())
            {
                var trans = dbCon.BeginTransaction();
                try
                {
                    int result = dbCon.Execute(strSql, model, trans);
                    string strRep = "update dbo.T_Report set Status='2',UpdateTime=@UpdateTime where Id=@ReportId";
                    dbCon.Execute(strRep, new { ReportId = model.ReportId, UpdateTime = DateTime.Now }, trans);
                    //提交事务
                    trans.Commit();
                    obj.model = result;
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "更新成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
                catch (Exception ex)
                {
                    //出现异常，事务Rollback
                    trans.Rollback();
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("更新表2季度生产情况表T_MulQuartProduc对象信息失败", ex);
                    return obj;
                }
            }
        }


        /// <summary>
        /// 读取导入的Excel数据
        /// </summary>
        /// <param name="pathName">导入文件路径</param>
        /// <param name="fileSuffix">文件后缀</param>
        /// <param name="sheetName">sheet名称</param>
        /// <param name="startRow">从第几行开始读取数据</param>
        /// <returns></returns>
        public List<MulQuartInfoModel> ExcelToModel(string pathName, string fileSuffix, string sheetName, int startRow)
        {

            IWorkbook workbook = null;
            ISheet sheet = null;
            List<MulQuartInfoModel> list = new List<MulQuartInfoModel>();
            FileStream fs = new FileStream(pathName, FileMode.Open, FileAccess.Read);
            switch (fileSuffix)
            {
                case ".xls":
                    workbook = new HSSFWorkbook(fs);
                    break;
                case ".xlsx":
                    workbook = new XSSFWorkbook(fs);
                    break;
                default:
                    workbook = new HSSFWorkbook(fs);
                    break;
            }
            if (!string.IsNullOrEmpty(sheetName))
            {
                sheet = workbook.GetSheet(sheetName);
                if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                {
                    sheet = workbook.GetSheetAt(0);
                }
            }
            else
            {
                sheet = workbook.GetSheetAt(0);
            }
            if (sheet != null)
            {
                //获取有数据的行数
                int rowCount = 0;
                for (int i = startRow; i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row != null)
                    {
                        rowCount = sheet.GetRow(i).RowNum;
                    }
                    else
                    {
                        break;
                    }
                }
                for (int i = startRow; i <= rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);
                    MulQuartInfoModel model = new MulQuartInfoModel();
                    if (row.GetCell(0) != null && row.GetCell(0).ToString() != "")
                    {
                        model.SeedSize = decimal.Parse(row.GetCell(0).ToString());
                    }
                    else
                    {
                        model.SeedSize = null;
                    }
                    if (row.GetCell(1) != null && row.GetCell(1).ToString() != "")
                    {
                        model.FreshCocoonYield = decimal.Parse(row.GetCell(1).ToString());
                    }
                    else
                    {
                        model.FreshCocoonYield = null;
                    }
                    if (row.GetCell(2) != null && row.GetCell(2).ToString() != "")
                    {
                        model.AveFreshCocoon = decimal.Parse(row.GetCell(2).ToString());
                    }
                    else
                    {
                        model.AveFreshCocoon = null;
                    }
                    if (row.GetCell(3) != null && row.GetCell(3).ToString() != "")
                    {
                        model.SmallRearSilk = decimal.Parse(row.GetCell(3).ToString());
                    }
                    else
                    {
                        model.SmallRearSilk = null;
                    }
                    if (row.GetCell(4) != null && row.GetCell(4).ToString() != "")
                    {
                        model.GridCluster = decimal.Parse(row.GetCell(4).ToString());
                    }
                    else
                    {
                        model.GridCluster = null;
                    }
                    if (row.GetCell(5) != null && row.GetCell(5).ToString() != "")
                    {
                        model.NextSeaOutPut = decimal.Parse(row.GetCell(5).ToString());
                    }
                    else
                    {
                        model.NextSeaOutPut = null;
                    }
                    if (row.GetCell(6) != null && row.GetCell(6).ToString() != "")
                    {
                        model.NextSeaFresh = decimal.Parse(row.GetCell(6).ToString());
                    }
                    else
                    {
                        model.NextSeaFresh = null;
                    }
                    list.Add(model);
                }
            }
            return list;
        }

        /// <summary>
        /// 添加
        /// </summary>
        public virtual ResResult<int> AddInfo(MulQuartInfoModel model)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"INSERT INTO dbo.T_MulQuartProduc";
            strSql += "(";
            strSql += "Id,";
            strSql += "ReportId,";
            strSql += "SeedSize,";
            strSql += "FreshCocoonYield,";
            strSql += "AveFreshCocoon,";
            strSql += "SmallRearSilk,";
            strSql += "GridCluster,";
            strSql += "NextSeaOutPut,";
            strSql += "NextSeaFresh)";
            strSql += " values(";
            strSql += "@Id,";
            strSql += "@ReportId,";
            strSql += "@SeedSize,";
            strSql += "@FreshCocoonYield,";
            strSql += "@AveFreshCocoon,";
            strSql += "@SmallRearSilk,";
            strSql += "@GridCluster,";
            strSql += "@NextSeaOutPut,";
            strSql += "@NextSeaFresh)";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    model.Id = CustomFun.GetGuid();
                    int result = dbCon.Execute(strSql, model);
                    if (result > 0)
                    {
                        obj.model = result;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "添加成功！";
                    }
                    else
                    {
                        obj.model = result;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "添加失败！数量为:" + result;
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("新增表2季度生产情况表T_MulQuartProduc对象信息失败", ex);
                return obj;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        public ResResult<int> DeleteData(string id)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"delete from dbo.T_MulQuartProduc where ReportId = @Id";
            int result;
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    result = dbCon.Execute(strSql, new { Id = id });
                    if (result > 0)
                    {
                        obj.model = result;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "删除成功！";
                    }
                    else
                    {
                        obj.model = result;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "删除失败！数量为:" + result;
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("删除表2季度生产情况表T_MulQuartProduc对象信息失败", ex);
                return obj;
            }
        }
        /// <summary>
        ///  季度生产情况统计--------(按季度统计)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResResult<List<MulQuartStatsModel>> GetStatsList(MulNowModel model)
        {
            string ProvinceCode = "530000000000";
            DictServices dictServices = new DictServices();
            if (!string.IsNullOrEmpty(model.FillInYear))
            {
                model.FillInYear = dictServices.GetPZKey(model.FillInYear, "ReportYear");
            }
            var paramlist = new DynamicParameters();
            paramlist.Add("AreaCode", model.AreaCode);
            paramlist.Add("FillInYear", model.FillInYear);
            paramlist.Add("ReportStatus", model.Status);
            ResResult<List<MulQuartStatsModel>> result = new ResResult<List<MulQuartStatsModel>>();
            /*县级统计代码*/
            string StrAreaSql = "select Area.Code AreaCode, Dict.DictText as FillYear, Area.Code,Area.FullName AreaName,Coord";
            StrAreaSql += ",ISNULL(SeedSize,0.00) SeedSize,ISNULL(FreshCocoonYield,0.00) FreshCocoonYield,ISNULL(AveFreshCocoon,0.00) AveFreshCocoon";
            StrAreaSql += ",ISNULL(SmallRearSilk,0.00) SmallRearSilk,ISNULL(GridCluster,0.00) GridCluster,ISNULL(NextSeaOutPut,0.00) NextSeaOutPut,ISNULL(NextSeaFresh,0.00) NextSeaFresh ";
            StrAreaSql += " from(";
            StrAreaSql += "select ";
            StrAreaSql += "case when grouping(Area.Code) = 1 then @AreaCode else Code end Code, ";
            StrAreaSql += "SUM(ISNULL(SeedSize,0.00) )SeedSize, ";//--发种量(张)
            StrAreaSql += "SUM(ISNULL(FreshCocoonYield,0.00)) FreshCocoonYield, ";// --鲜茧产量(吨)	
            //StrAreaSql += "SUM(ISNULL(AveFreshCocoon,0.00)) AveFreshCocoon,  ";
            //--鲜茧均价(元/公斤)
            StrAreaSql += "SUM(ISNULL(((((CASE TimesCycle WHEN '春季' THEN FreshCocoonYield ELSE 0 END)*(CASE TimesCycle WHEN '春季' THEN AveFreshCocoon ELSE 0 END)) ";
            StrAreaSql += "+ ((CASE TimesCycle WHEN '夏季' THEN FreshCocoonYield ELSE 0 END)*(CASE TimesCycle WHEN '夏季' THEN AveFreshCocoon ELSE 0 END))";
            StrAreaSql += "+ ((CASE TimesCycle WHEN '正秋' THEN FreshCocoonYield ELSE 0 END)*(CASE TimesCycle WHEN '正秋' THEN AveFreshCocoon ELSE 0 END))";
            StrAreaSql += "+ ((CASE TimesCycle WHEN '晚秋' THEN FreshCocoonYield ELSE 0 END)*(CASE TimesCycle WHEN '晚秋' THEN AveFreshCocoon ELSE 0 END)))),0.00)) AveFreshCocoon,";

            StrAreaSql += "SUM(ISNULL(SmallRearSilk,0.00)) SmallRearSilk, ";//--小蚕共育(张)
            StrAreaSql += "SUM(ISNULL(GridCluster,0.00)) GridCluster, ";//--	方格簇(张)
            StrAreaSql += "SUM(ISNULL(NextSeaOutPut,0.00)) NextSeaOutPut, ";//--预计下季度发种量(张)
            StrAreaSql += "SUM(ISNULL(NextSeaFresh,0.00)) NextSeaFresh ";// --预计下季度鲜茧产量(吨)
            StrAreaSql += "from  T_Report Report left join T_MulQuartProduc MulQuartProduc on Report.Id=MulQuartProduc.ReportId right join T_Area Area on Report.AreaCode=Area.Code ";
            StrAreaSql += "where ";
            StrAreaSql += "Area.ParentCode = @AreaCode  and Report.Status=@ReportStatus and Report.FillInYear=@FillInYear  ";
            if (!string.IsNullOrEmpty(model.TimesCycle))
            {
                paramlist.Add("TimesCycle", model.TimesCycle);
                StrAreaSql += " and TimesCycle=@TimesCycle ";
            }
            StrAreaSql += "group by rollup(Area.Code)) tt1 left join T_Area Area  on tt1.Code=Area.Code  inner join T_Dict Dict  on Dict.GroupCode='ReportYear' and DictValue=@FillInYear  ";
            StrAreaSql += "where area.ParentCode=@AreaCode  or area.Code=@AreaCode ";
            StrAreaSql += "order by AreaCode asc ";

            /*市级统计代码*/
            string StrCitySql = "select Area.Code AreaCode, Dict.DictText FillYear,area.FullName AreaName,Coord";
            StrCitySql += ",ISNULL(SeedSize,0.00) SeedSize,ISNULL(FreshCocoonYield,0.00) FreshCocoonYield,ISNULL(AveFreshCocoon,0.00) AveFreshCocoon";
            StrCitySql += ",ISNULL(SmallRearSilk,0.00) SmallRearSilk,ISNULL(GridCluster,0.00) GridCluster,ISNULL(NextSeaOutPut,0.00) NextSeaOutPut,ISNULL(NextSeaFresh,0.00) NextSeaFresh   ";
            StrCitySql += " from (select ";
            StrCitySql += "case when grouping(Area.ParentCode)=1 then @AreaCode  else ParentCode end ParentCode, ";
            StrCitySql += "SUM(ISNULL(SeedSize,0.00) ) SeedSize, ";//--发种量(张)
            StrCitySql += "SUM(ISNULL(FreshCocoonYield,0.00)) FreshCocoonYield, ";// --鲜茧产量(吨)	
            //StrCitySql += "SUM(ISNULL(AveFreshCocoon,0.00)) AveFreshCocoon,  ";//--鲜茧均价(元/公斤)

            //--鲜茧均价(元/公斤)
            StrCitySql += "SUM(ISNULL(((((CASE TimesCycle WHEN '春季' THEN FreshCocoonYield ELSE 0 END)*(CASE TimesCycle WHEN '春季' THEN AveFreshCocoon ELSE 0 END)) ";
            StrCitySql += "+ ((CASE TimesCycle WHEN '夏季' THEN FreshCocoonYield ELSE 0 END)*(CASE TimesCycle WHEN '夏季' THEN AveFreshCocoon ELSE 0 END))";
            StrCitySql += "+ ((CASE TimesCycle WHEN '正秋' THEN FreshCocoonYield ELSE 0 END)*(CASE TimesCycle WHEN '正秋' THEN AveFreshCocoon ELSE 0 END))";
            StrCitySql += "+ ((CASE TimesCycle WHEN '晚秋' THEN FreshCocoonYield ELSE 0 END)*(CASE TimesCycle WHEN '晚秋' THEN AveFreshCocoon ELSE 0 END)))),0.00)) AveFreshCocoon,";

            StrCitySql += "SUM(ISNULL(SmallRearSilk,0.00)) SmallRearSilk, ";//--小蚕共育(张)
            StrCitySql += "SUM(ISNULL(GridCluster,0.00)) GridCluster, ";//--	方格簇(张)
            StrCitySql += "SUM(ISNULL(NextSeaOutPut,0.00)) NextSeaOutPut, ";//--预计下季度发种量(张)
            StrCitySql += "SUM(ISNULL(NextSeaFresh,0.00)) NextSeaFresh ";// --预计下季度鲜茧产量(吨)
            StrCitySql += "from t_report t1 ";
            StrCitySql += "left join T_MulQuartProduc t2 on t2.ReportId = t1.Id ";
            StrCitySql += "right join T_Area Area on Area.Code = t1.AreaCode ";
            StrCitySql += "where ParentCode!=@AreaCode  and t1.FillInYear=@FillInYear and t1.Status=@ReportStatus ";
            if(!string.IsNullOrEmpty(model.TimesCycle))
            {
                paramlist.Add("TimesCycle", model.TimesCycle);
                StrCitySql += " and TimesCycle=@TimesCycle ";
            }
            StrCitySql += "group by rollup(Area.ParentCode) ";
            StrCitySql += ") t left join T_Area  area on area.Code = t.ParentCode ";
            StrCitySql += "inner join T_Dict Dict  on Dict.GroupCode='ReportYear' and DictValue=@FillInYear ";
            StrCitySql += "where area.ParentCode=@AreaCode  or area.Code=@AreaCode ";
            StrCitySql += "order by AreaCode asc ";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    List<MulQuartStatsModel> list = new List<MulQuartStatsModel>();
                    if (model.AreaCode != ProvinceCode)//不为省级用户
                    {
                        list = dbCon.Query<MulQuartStatsModel>(StrAreaSql, paramlist).ToList();
                        //int num = list.Where(s => s.AveFreshCocoon != 0).Count() - 1;
                        foreach (var item in list)
                        {
                            if (item.FreshCocoonYield != 0) {
                                string ave = Math.Round((double)(item.AveFreshCocoon / item.FreshCocoonYield), 2).ToString();
                                item.AveFreshCocoon = Convert.ToDecimal(ave);
                            }else
                            {
                                item.AveFreshCocoon = 0;
                            }
                        }
                        //result.model = list;
                    }
                    else
                    {
                        list = dbCon.Query<MulQuartStatsModel>(StrCitySql, paramlist).ToList();
                        foreach (var item in list) {
                            if (item.FreshCocoonYield != 0)
                            {
                                string ave = Math.Round((double)(item.AveFreshCocoon / item.FreshCocoonYield), 2).ToString();
                                item.AveFreshCocoon = Convert.ToDecimal(ave);
                            }
                            else
                            {
                                item.AveFreshCocoon = 0;
                            }
                        }
                    }
                    List<MulQuartStatsModel> list2 = new List<MulQuartStatsModel>();
                    //list.Where(s => s.AreaCode == model.AreaCode).FirstOrDefault().AreaName = "合计";
                    //MulQuartStatsModel m = list.Where(s => s.AreaName == "合计").FirstOrDefault();
                    //list.Remove(m);
                    //list2.Add(m);
                    for (var i = 0; i < list.Count; i++)
                    {
                        list2.Add(list[i]);
                    }
                    result.model = list2;

                    if (list != null)
                    {
                        result.status = DefaultKey.SuccessResult;
                        result.message = "获取季度生产情况统计数据成功！";
                    }
                    else
                    {
                        result.status = DefaultKey.InfoResult;
                        result.message = "获取季度生产情况统计数据失败！";
                    }
                    dbCon.Dispose();//数据库连接释放
                }
            }
            catch (Exception ex)
            {
                result.status = DefaultKey.ErrorResult;
                result.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取季度生产情况统计数据失败", ex);
            }
            return result;
        }
        public ResResult<List<MulQuartStatsModel>> GetDetailStats(MulNowModel model)
        {
            ResResult<List<MulQuartStatsModel>> res = new ResResult<List<MulQuartStatsModel>>();
            List<MulQuartStatsModel> list = new List<MulQuartStatsModel>();
            string ProvinceCode = DefaultKey.ProvinceCode;
            string FillInYear = model.FillInYear;
            try
            {
                if (model.AreaCode == ProvinceCode)
                {
                    var First = GetStatsList(model).model;
                    //First[0].AreaName = "合计";
                    list.Add(First[0]);//省级汇总合计
                    foreach (var item in First)
                    {
                        if (item.AreaCode != ProvinceCode)
                        {
                            MulNowModel model2 = new MulNowModel();
                            model2.FillInYear = FillInYear;
                            model2.AreaCode = item.AreaCode;
                            model2.Status = model.Status;
                            var Second = GetStatsList(model2).model;
                            list.Add(item);
                            foreach (var item2 in Second)
                            {
                                if (model2.AreaCode != item2.AreaCode)
                                {
                                    list.Add(item2);
                                }
                            }
                        }
                    }
                }
                else
                {
                    list = GetStatsList(model).model;//数据获取
                }
            }
            catch (Exception ex)
            {
                res.model = list;
                res.message = "获取统计数据详情失败" + ex.ToString().Trim();
                res.status = DefaultKey.SuccessResult;
            }
            if (list != null)
            {
                res.model = list;
                res.message = "获取统计数据详情成功";
                res.status = DefaultKey.SuccessResult;
            }
            else
            {
                res.message = "获取统计数据详情成失败";
                res.status = DefaultKey.ErrorResult;
            }
            return res;
        }
        /// <summary>
        /// 导出统计数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public MemoryStream MethodStats(MulNowModel model)
        {
            string FillInYear = model.FillInYear;
            AreaServices areaServices = new AreaServices();
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string AreaName = areaServices.GetByCodeModel(model.AreaCode).model.Name == "云南省" ? "云南省_县(市、州)" : areaServices.GetByCodeModel(model.AreaCode).model.Name;//获取当前行政区划名称
            getExcelStatsList(workbook, GetDetailStats(model).model, AreaName,model.TimesCycle);//省级汇总(针对曲线)
            if (model.AreaCode == DefaultKey.ProvinceCode)//判断当前用户是否为省级用户
            {
                AreaName = areaServices.GetByCodeModel(model.AreaCode).model.Name;
                model.FillInYear = FillInYear;
                getExcelStatsList(workbook, GetStatsList(model).model, AreaName + "_州市", model.TimesCycle);//省级汇总(针对州市)
                var areaList = areaServices.GetPrefectureList();//获取州市级列表
                foreach (var areaCode in areaList)
                {
                    model.AreaCode = areaCode;
                    model.FillInYear = FillInYear;
                    getExcelStatsList(workbook, GetDetailStats(model).model, areaServices.GetByCodeModel(areaCode).model.Name, model.TimesCycle);
                }
            }
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }

        /// <summary>
        /// 获取时间趋势图数据列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResResult<List<MulQuartStatsModel>> GetStatsByTimeList(MulNowModel model)
        {
            DictServices dictServices = new DictServices();
            List<Select> listDict = dictServices.GetListByGroupCode("ReportYear").model;
            ResResult<List<MulQuartStatsModel>> result = new ResResult<List<MulQuartStatsModel>>();
            List<MulQuartStatsModel> list = new List<MulQuartStatsModel>();
            if (listDict.Count > 0)
            {
                if (!string.IsNullOrEmpty(model.AreaCode))
                {
                    for (var i = 0; i < listDict.Count; i++)
                    {
                        model.FillInYear = listDict[i].label;
                        List<MulQuartStatsModel> listOne = GetStatsList(model).model;
                        if (listOne.Count > 0)
                        {
                            list.Add(listOne[0]);
                        }
                    }
                    if (list.Count > 0)
                    {
                        result.message = "时间趋势数据列表获取成功";
                        result.model = list.OrderBy(s => s.FillYear).ToList();
                        result.status = DefaultKey.SuccessResult;
                    }
                    else
                    {
                        result.message = "时间趋势数据列表为空";
                        result.status = DefaultKey.InfoResult;
                    }
                }
                else
                {
                    result.message = "时间趋势数据列表失败,当前地区不存在";
                    result.status = DefaultKey.ErrorResult;
                }
            }
            else
            {
                result.message = "时间趋势数据列表失败,时间为空";
                result.status = DefaultKey.ErrorResult;
            }
            return result;
        }
        /// <summary>
        /// 返回excel工作簿
        /// </summary>
        /// <param name="workbook">工作簿</param>
        /// <param name="sheet">子表</param>
        /// <param name="model"></param>
        /// <param name="AreaName">地区名称</param>
        /// <returns></returns>
        public HSSFWorkbook getExcelStatsList(HSSFWorkbook workbook, List<MulQuartStatsModel> list, string AreaName,string TimesCycle)
        {
            FileStream file = null;
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\ExcelStats.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            
            HSSFSheet sheet = null;
            if(!string.IsNullOrEmpty(TimesCycle))
            {
                sheet = templateBook.GetSheet("MulQuartProduc") as HSSFSheet;//读取模板所在sheet位置
            }
            else
            {
                sheet = templateBook.GetSheet("MulYearProduc") as HSSFSheet;//读取模板所在sheet位置
            }
            //List<VegBasicInfoStatsModel> list = new List<VegBasicInfoStatsModel>();
            //list = null;
            //list = GetDetailStats(model).model;
            #region 县市级表格样式
            HSSFRow row = (HSSFRow)sheet.GetRow(1);//读取模板第二行
            var style = row.GetCell(0).CellStyle;//读取模板第二行第一单元格样式并保存
            #endregion
            row.GetCell(0).CellStyle = style;//对第二行第一单元格设置原来样式
            #region 州市级表格样式
            //var style2 = row.GetCell(1).CellStyle;
            var styleOneArea = Common.GetOneAreaCellStyle(templateBook, style);
            var styleOneCity = Common.GetOneCityCellStyle(templateBook, style);
            var styleIntCity = Common.GetIntCityCellStyle(templateBook, style); 
            var styleIntArea = Common.GetIntAreaCellStyle(templateBook, style);

            #endregion
            if (list != null)
            {
                int cellCount = 6;
                for (int i = 0; i < list.Count; i++)
                {
                    HSSFRow datarow = (HSSFRow)sheet.CreateRow(i + 2);
                    datarow.CreateCell(0).SetCellValue(list[i].AreaName == null ? "" : list[i].AreaName.ToString());
                    datarow.CreateCell(1).SetCellValue(list[i].SeedSize == null ? 0 : Convert.ToDouble(list[i].SeedSize));
                    //datarow.GetCell(1).CellStyle.DataFormat=
                    datarow.CreateCell(2).SetCellValue(list[i].FreshCocoonYield == null ? 0.0 : Convert.ToDouble(list[i].FreshCocoonYield));
                    datarow.CreateCell(3).SetCellValue(list[i].AveFreshCocoon == null ?0.0 : Convert.ToDouble(list[i].AveFreshCocoon));
                    datarow.CreateCell(4).SetCellValue(list[i].SmallRearSilk == null ? 0 : Convert.ToDouble(list[i].SmallRearSilk));
                    datarow.CreateCell(5).SetCellValue(list[i].GridCluster == null ? 0 : Convert.ToDouble( list[i].GridCluster));
                    if (!string.IsNullOrEmpty(TimesCycle))
                    {
                        cellCount = 8;
                        datarow.CreateCell(6).SetCellValue(list[i].NextSeaOutPut == null ? 0.0 : Convert.ToDouble(list[i].NextSeaOutPut));
                        datarow.CreateCell(7).SetCellValue(list[i].NextSeaFresh == null ? 0.0 : Convert.ToDouble(list[i].NextSeaFresh));
                    }
                    for (int j = 0; j < cellCount; j++)
                    {
                        if (!CustomFun.IsCity(list[i].AreaCode))
                        {//省级和州市级
                            datarow.GetCell(j).CellStyle = styleOneCity;
                            if (j == 1 || j == 4 || j == 5)
                            {
                                datarow.GetCell(j).CellStyle = styleIntCity;
                            }
                        }
                        else//县级
                        {
                            datarow.GetCell(j).CellStyle = styleOneArea;
                            if (j == 1 || j == 4 || j == 5)
                            {
                                datarow.GetCell(j).CellStyle = styleIntArea;
                            }
                        }
                    }
                }
                sheet.CopyTo(workbook, AreaName, true, true);
            }
            return workbook;
        }
    }
}